﻿using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows;

namespace Super.Hmi.Behavior
{
    /// <summary>
    /// Popup 事件
    /// </summary>
    public class PopupBehavior
    {
        public static bool GetCloseOnClickOutside(DependencyObject obj)
        {
            return (bool)obj.GetValue(CloseOnClickOutsideProperty);
        }
        public static void SetCloseOnClickOutside(DependencyObject obj, bool value)
        {
            obj.SetValue(CloseOnClickOutsideProperty, value);
        }
        // 鼠标失焦事件
        public static readonly DependencyProperty CloseOnClickOutsideProperty = DependencyProperty.RegisterAttached("CloseOnClickOutside", typeof(bool), typeof(PopupBehavior), new PropertyMetadata(false, OnCloseOnClickOutsideChanged));
        private static void OnCloseOnClickOutsideChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Popup popup)
            {
                popup.Loaded -= Popup_Loaded;
                if ((bool)e.NewValue)
                {
                    popup.Loaded += Popup_Loaded;
                }
            }
        }
        private static void Popup_Loaded(object sender, RoutedEventArgs e)
        {
            var popup = sender as Popup; if (popup == null) return;
            var window = Window.GetWindow(popup); if (window == null) return;
            window.PreviewMouseDown += (s, args) =>
            {
                // 检查点击是否在 Popup 内部
                //if (popup.Child is FrameworkElement child && !child.IsMouseOver && !(popup.Parent is UIElement parent && parent.IsMouseOver))                
                if (popup.Child is FrameworkElement child && !child.IsMouseOver)
                {
                    // 如果设置了 CloseCommand，则执行命令
                    var closeCommand = GetCloseCommand(popup);
                    if (closeCommand != null && closeCommand.CanExecute(null))
                    {
                        closeCommand.Execute(null);
                    }
                    else
                    {
                        // 否则直接关闭 Popup
                        popup.IsOpen = false;
                    }
                }
            };
        }
        public static ICommand GetCloseCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CloseCommandProperty);
        }
        public static void SetCloseCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CloseCommandProperty, value);
        }
        // 添加关闭命令的附加属性
        public static readonly DependencyProperty CloseCommandProperty = DependencyProperty.RegisterAttached("CloseCommand", typeof(ICommand), typeof(PopupBehavior), new PropertyMetadata(null));
    }
}
